const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { Unauthorized } = require('http-errors');
const { success, failure } = require('../utils/responses');

module.exports = async (req, res, next) => {
  try {
    const token = req.headers.token || req.query.token;

    if (!token) {
      throw new Unauthorized('当前接口需要登录');
    }
    const decoded = jwt.verify(token, process.env.SECRET);
    //从token中解析出用户id
    const { userId } = decoded;

    // 如果通过验证，将 userId 对象挂载到 req 上，方便后续中间件或路由使用
    req.userId = userId;
    next();
  } catch (error) {
    failure({ res, error, message: '请先登录', code: 401 });
  }
};
